package com.example.compose.timer

import android.os.CountDownTimer
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow

class TimerViewModel: ViewModel() {

    companion object {
        const val totalTime = 60 * 1000L
        const val interval = 1 * 1000L
    }

    private var timer: CountDownTimer? = null

    var remainingTime = MutableStateFlow(totalTime)
        private set
    var isRunning = MutableStateFlow(false)
        private set

    private fun createTimer() {
        timer = object : CountDownTimer(totalTime, interval) {
            override fun onTick(millisUntilFinished: Long) {
                remainingTime.value = millisUntilFinished
            }

            override fun onFinish() {
                remainingTime.value = totalTime
                isRunning.value = false
            }
        }
    }

    fun startTimer() {
        createTimer()
        timer?.start()
        isRunning.value = true
    }

    fun onResetTimer() {
        if (isRunning.value) {
            timer?.cancel()
            remainingTime.value = totalTime
            isRunning.value = false
        }
    }

    override fun onCleared() {
        super.onCleared()
        timer?.cancel()
        remainingTime.value = totalTime
    }
}

